package org.huhuiyu.easyui.action;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

//统一处理json应答的工具类
public class JsonActionUtil {
	private String format = "yyyy年MM月dd日"; //日期输出格式

	private boolean success; // 处理是否成功
	// json的数据集合
	private Map<String, Object> dataMap = new HashMap<String, Object>();

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public void putData(String key, Object data) {
		dataMap.put(key, data);
	}

	public Object remove(String key) {
		return dataMap.remove(key);
	}

	public void clear() {
		dataMap.clear();
	}

	// 转换数据到json格式字符串
	public String getJson() {
		JSONObject json = new JSONObject();
		json.put("success", success);
		for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
			json.put(entry.getKey(), entry.getValue());
		}
		return JSON.toJSONStringWithDateFormat(json, format,
				SerializerFeature.WriteDateUseDateFormat,
				SerializerFeature.PrettyFormat,
				SerializerFeature.DisableCircularReferenceDetect);
	}

	public void write() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		out.print(getJson());
		out.close();
	}

	public static void writeText(String text) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		out.print(text);
		out.close();
	}

	public static JsonActionUtil getSuccessJson(String key, Object data) {
		JsonActionUtil util = new JsonActionUtil();
		util.setSuccess(true);
		util.putData(key, data);
		return util;
	}

	public static JsonActionUtil getFailJson(String message) {
		JsonActionUtil util = new JsonActionUtil();
		util.setSuccess(false);
		util.putData("message", message);
		return util;
	}

}
